package com.yueke.gemini.controller;

import java.io.IOException;

import com.yueke.gemini.entity.UserInfo;
import com.yueke.gemini.entity.WeixinBackInfo;
import com.yueke.gemini.utils.Commons;
import com.yueke.gemini.utils.Tools;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * created by admin 2020/3/28 16:24
 */
@Controller
public class AuthController {

    ObjectMapper mapper = new ObjectMapper();

    /**
     *
     * @param code
     * @return
     */
    @RequestMapping(value="/renzheng",method=RequestMethod.GET)
    @ResponseBody
    public String authMehtod(String code){
        System.out.println("code:"+code);
        String jsonText ="";
        StringBuffer url=new StringBuffer("https://api.weixin.qq.com/sns/oauth2/access_token?");
        url.append("appid=").append(Commons.weixinConfig.getAppid()).append("&");
        url.append("secret=").append(Commons.weixinConfig.getSecret()).append("&");
        url.append("code=").append(code).append("&");
        url.append("grant_type=").append(Commons.weixinConfig.getGrant_type());
        System.out.println("url:"+url);
        jsonText = Tools.getStaticString(url.toString());
        System.out.println("jsonText:"+jsonText);
        WeixinBackInfo weixinBackInfo =null;
        try {
            weixinBackInfo = mapper.readValue(jsonText, WeixinBackInfo.class);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println("openId:"+weixinBackInfo.getOpenid());
        UserInfo userInfo = new UserInfo();
        if(weixinBackInfo.getErrcode()==null){
            userInfo=getUserInfo(weixinBackInfo);
            System.out.println("userInfo::::"+userInfo.getNickname());
        }
        return userInfo.getUnionid() ;
    }


    public UserInfo getUserInfo(WeixinBackInfo backInfo){
        StringBuffer url = new StringBuffer("https://api.weixin.qq.com/sns/userinfo?");
        String jsonText ="";
        url.append("access_token=").append(backInfo.getAccess_token()).append("&");
        url.append("openid=").append(backInfo.getOpenid()).append("&");
        url.append("lang=zh_CN");
        System.out.println("UserInfo_Url:"+url);
        jsonText=Tools.getStaticString(url.toString());
        System.out.println("UserInfo_Url:"+jsonText);
        UserInfo userInfo =null;
        try {
            userInfo = mapper.readValue(jsonText, UserInfo.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return userInfo;
    }
}
